package org.example.dynamic_planning;

import java.util.Arrays;

public class Divide_equal_sum_subsets {
    public static void main(String[] args) {
        //分割等和子集

        //给你一个 只包含正整数 的 非空 数组 nums 。请你判断是否可以将这个数组分割成两个子集，使得两个子集的元素和相等。
        int[] nums = {1,2,3,6};
        boolean b = canPartition(nums);
        System.out.println(b);
    }

    public static boolean canPartition(int[] nums) {
        Arrays.sort(nums);
        int sum = 0;
        double sum2 = 0;
        for (int i = 0; i < nums.length; i++) {
            sum+=nums[i];
            sum2+=nums[i];
        }
        if (sum/2 != sum2/2) return false;
        if (nums[nums.length-1] > sum/2) return false;
        int[][] dp = new int[nums.length][sum/2+1];
        for (int[] arr : dp) {
            Arrays.fill(arr,0);
        }
        for (int i = nums[0]; i < sum / 2 + 1; i++) {
            dp[0][i] = nums[0];
        }
        for (int i = 1; i < nums.length; i++) {
            for (int j = 1; j < sum / 2 + 1; j++) {
                if (nums[i] > j){
                    dp[i][j] = dp[i-1][j];
                }else {
                    dp[i][j] = Math.max(dp[i-1][j],dp[i-1][j-nums[i]]+nums[i]);
                }
            }
        }
        return dp[nums.length-1][sum/2] == sum/2;
    }
}
